<?php include("session.inc.php"); ?>
<?php require_once("../common/config.inc.php");?>
<?php include("../common/db.inc.php"); ?>
<?php
global $currentUser,$divDisplayStyle,$operateResult,$currentDate;

	init();		
	
	function init(){
		$GLOBALS[divDisplayStyle]=array();
		$operation=$_POST["operation"];
		//handle post request - modify user 
		if($operation && ($operation=="ModifyUserWithoutPass" || $operation=="ModifyUserWithPass")){
			$GLOBALS[divDisplayStyle]["oprateDiv"]="display:none";
			$GLOBALS[divDisplayStyle]["oprateResultDiv"]="display:inline";
			updateUser();
			$GLOBALS[operateResult]="Modify user succeed!";
		}else{
			$GLOBALS[divDisplayStyle]["oprateDiv"]="display:inline";
			$GLOBALS[divDisplayStyle]["oprateResultDiv"]="display:none";		
			//handle get request - link to modify user page
			$userid=$_GET["userid"];	
			if($userid && $userid!="")	{
				getUser($userid);			
			}else{
			     header("Location: UserList.php");
			     exit;			
			}
		}
	}
	
	function getUser($userid){
		$sql = "SELECT * FROM medcdb.t_user where userid='$userid'";
		$connection=getMEDCConnection();
		$userArray=executeQuery($sql,$connection);
		$GLOBALS[currentUser]=$userArray[0];
		//echo "user id is ".$userid;
		//echo "<br/>user number is ".count($userArray);
		//echo "<br/> columns num is ".$GLOBALS[currentUser]['userid'];
	}	
	
	function updateUser(){
		//$columnNames=array("userid","usertype","valto","contactinfo","comment","createdate");
		$userid=$_POST["userid"];
		$password=$_POST["password"];
		$usertype=$_POST["usertype"];
		$valfrom=$_POST["valfrom"];
		$valto=$_POST["valto"];
		$contactinfo=$_POST["contactinfo"];
		$comment=$_POST["comment"];
		$createdate=$_POST["createdate"];		
		$sql=null;
		
		if($_POST["operation"]=="ModifyUserWithoutPass"){
			//echo "<br/> ModifyUserWithoutPass! ";
			$sql = "update medcdb.t_user set usertype='$usertype',valfrom='$valfrom',valto='$valto'," .
					"contactinfo='$contactinfo',comment='$comment',createdate='$createdate'" .
					"where userid='$userid'";
		}else{
			//echo "<br/> ModifyUserWithPass! ";
			$password=md5($password);
			$sql = "update medcdb.t_user set password='$password',usertype='$usertype',valfrom='$valfrom',valto='$valto'," .
					"contactinfo='$contactinfo',comment='$comment',createdate='$createdate'" .
					"where userid='$userid'";			
			
		}	
		//echo("sql is:".$sql);		
		$connection=getMEDCConnection();
		executeUpdate($sql,$connection);
	}		
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="keywords" content="" />
<meta name="Description" content="" />
<meta name="author" content="" />
<title>User Modify Page</title>
<link rel="stylesheet" type="text/css" href="../css/medc.css" />
<script language="JavaScript" type="text/javaScript" src="../js/medc_common.js"></script>
<script language="JavaScript" type="text/javaScript" src="../js/CalendarPopup.js"></script>
<script language="JavaScript" type="text/javascript">	
	var ValidateFromDateCalendar=null;
	var ValidateToDateCalendar=null;
	
	function init(){
	    //set the scheduleTabCalendar
	    ValidateToDateCalendar = new CalendarPopup("ValidateToDateCalendarDiv");
	    ValidateToDateCalendar.setCssPrefix("TEST");
	    ValidateToDateCalendar.setReturnFunction("calendarReturnFunction");
	    
	    ValidateFromDateCalendar = new CalendarPopup("ValidateFromDateCalendarDiv");
	    ValidateFromDateCalendar.setCssPrefix("TEST");
	    ValidateFromDateCalendar.setReturnFunction("calendarReturnFunction");	    
	}
		
	function resetPass(){
	    var isConfirm = window.confirm("Are you sure to reset the user's password?");
	    if (isConfirm == false) {
	        return;
	    }	
		var newPass=getRandomCode(8);
		document.getElementById("password").readOnly=false;
		document.getElementById("password").value=newPass;
	}
	
	function calendarReturnFunction(y, m, d) {
	    if (window.CP_targetInput != null) {
	        var dt = new Date(y, m - 1, d, 0, 0, 0);
	        if (window.CP_calendarObject != null) {
	            window.CP_calendarObject.copyMonthNamesToWindow();
	        }
	        window.CP_targetInput.value = formatDate(dt, window.CP_dateFormat);
	    } else {
	        alert('Use setReturnFunction() to define which function will get the clicked results!');
	    }
	}
		
	function clickCalendar(calendarName){
		var inputName=null;
		var anchorName=null;
		var calendarObj=null;
		if(calendarName=="ValidateToDateCalendar"){
			inputName="valto";
			anchorName="ValidateToDateCalendarImg";
			calendarObj=ValidateToDateCalendar;			
		}else if(calendarName=="ValidateFromDateCalendar"){
			inputName="valfrom";
			anchorName="ValidateFromDateCalendarImg";
			calendarObj=ValidateFromDateCalendar;					
		}
		var inputObj=document.getElementById(inputName);
		calendarObj.select(inputObj,anchorName,'yyyy-MM-dd');	
		return false;	
	}	
	
	function doPost(operation){
		if(operation=="saveUser"){
		    var isConfirm = window.confirm("Are you sure to save changes?");
		    if (isConfirm == false) {
		        return;
		    }				
		}
		if(validate()==false){
			return;
		}
		//check if update password
		var password=document.getElementById("password").value;
		if(password.trim()==""){
			//alert("userPass is empty!");
			document.getElementById("operation").value="ModifyUserWithoutPass";
		}else{			
			//alert("userPass is not empty! - "+password);
			document.getElementById("operation").value="ModifyUserWithPass";
		}
		//document.forms["medcform"].attributes["action"]="UserModify.php";
		document.forms["medcform"].submit();
	}
	
	function validate(){
		if(document.getElementById("password").readOnly==false){			
			var password=document.getElementById("password").value;
			if(isWhitespace(password)){
				alert("password can not be empty!");		
				return false;				
			}else if(password.length>8 || password.length<4){
				alert("password length is 4-8!")			
				return false;
			}else if(isNumAndAlpha(password,"password")==false){				
				alert("password should only contain numbers and alphabets!");			
				return false;
			}
		}
		//check Validate Date
		var validateToDate=document.getElementById("valto").value;
		if(isWhitespace(validateToDate)){
			alert("validate to date can not be empty!");		
			return false;				
		}
		var validateFromDate=document.getElementById("valfrom").value;
		if(isWhitespace(validateFromDate)){
			alert("validate from date can not be empty!");		
			return false;				
		}			
		return true;
	}
</script>
</head>
<body onload="init()">
<!--Top area-->
	<div id="toparea">
		<?php include "../common/header.inc.php"?>
	</div>
	<div id="menu">
		<?php include "AdminMenu.inc.php";?>
	</div>	

	<!--Main area-->
	<div id="mainarea">
		<form method="post" action="UserModify.php" name="medcform">
		<input type="hidden" name="operation" id="operation" />
		<div id="oprateDiv" style="<? echo $GLOBALS[divDisplayStyle]["oprateDiv"] ?>" >
			<table>
				<tr>
					<td align="left"><label for="userid">User Id</label></td>
					<td align="left"><input type="text" name="userid" id="userid" maxLength="30" size="20" readonly="true" value="<? echo $GLOBALS[currentUser]['userid']?>"/><td>
				</tr>
				<tr>
					<td align="left" style="width:120px;"><label for="usertype">User Type</label></td>
					<td align="left">
					<select name="usertype" id="usertype">
					<?
					$userTypes=array('Normal' => '2', 'Admin' => '1');
					$checked="";
					foreach ($userTypes as $key => $value) {	    		    
						if($value==$GLOBALS[currentUser]['usertype']){
							$checked="selected";
						}else{
							$checked="";
						}
					?>
					<option value="<? echo $value ?>" <? echo $checked ?> ><? echo $key ?> </option>
					<?}?>

					</select>
					<td>
				</tr>	
				<tr>
					<td align="left" valign="bottom"><label for="password">Password</label></td>
					<td align="left">			
						<input type="text" name="password" id="password" maxLength="10" size="20" readonly="true" />			
						<input type="button" name="ResetPassword" value="Reset" id="ModifyUser"
						onclick="resetPass()" />
						<label for="password" >(4-8 numbers and alphabets)</label>
					<td>
				</tr>
				<tr>
					<td align="left"><label for="valfrom">ValFrom Date</label></td>
					<td nowrap="true"align="left">		
						<div id="ValidateFromDateDiv"><input name="valfrom" id="valfrom" type="text" title="Validate From Date" value="<? echo $GLOBALS[currentUser]['valfrom']?>"/>  
							<div id="ValidateFromDateCalendarDiv" style="position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"></div>
							<img src="../images/icon-select-date.gif" alt="select date icon" name="ValidateFromDateCalendarImg" id="ValidateFromDateCalendarImg" height="14" width="13"
							onclick="clickCalendar('ValidateFromDateCalendar')" />
						</div>		
					</td>
				</tr>					
				<tr>
					<td align="left"><label for="valto">ValTo Date</label></td>
					<td nowrap="true"align="left">		
						<div id="ValidateToDateDiv"><input name="valto" id="valto" type="text" title="Validate To Date" value="<? echo $GLOBALS[currentUser]['valto']?>"/>  
							<div id="ValidateToDateCalendarDiv" style="position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"></div>
							<img src="../images/icon-select-date.gif" alt="select date icon" name="ValidateToDateCalendarImg" id="ValidateToDateCalendarImg" height="14" width="13"
							onclick="clickCalendar('ValidateToDateCalendar')" />
						</div>		
					</td>
				</tr>	
				<tr>
					<td align="left" valign="top" ><label for="contactinfo">Contact</label></td>
					<td align="left"><textarea id="contactinfo" name="contactinfo" rows="3" ><? echo $GLOBALS[currentUser]['contactinfo']?></textarea><td>
				</tr>	
				<tr>
					<td align="left" valign="top" ><label for="comment">Comment</label></td>
					<td align="left"><textarea id="comment" name="comment" rows="3" ><? echo $GLOBALS[currentUser]['comment']?></textarea><td>
				</tr>		
				<tr>
					<td align="left"><label for="createdate">Create Date</label></td>
					<td align="left"><input type="text" name="createdate" id="createdate" maxLength="30" size="20" readonly="true" value="<? echo $GLOBALS[currentUser]['createdate']?>"/><td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td>
						<div align="right">
							<input type="button" name="ModifyUser" value="Save" id="ModifyUser" onclick="doPost('saveUser')" />
						</div>
					</td>
				</tr>
			</table>
		</div>
		<div id="operateResultDiv" style="<? echo $GLOBALS[divDisplayStyle]["operateResultDiv"] ?>" >
			<div align="center">
				<p><?php echo $GLOBALS[operateResult]; ?></p> 
			</div>
		</div>
		</form>
	</div>
	
	<div class="myclear"></div>
	<div id="footer">
		<?php include "../common/footer.inc.php";?>
	</div>
</body>
</html>
